<template>
  <div class="inventory-warning-page">
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="filters" label-width="80px" class="filter-form">
        <el-form-item label="货品">
          <el-input
            v-model="filters.productKeyword"
            placeholder="请输入货品名称"
            clearable
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="货品类型">
          <el-cascader
            v-model="filters.productTypeId"
            :options="productTypeOptions"
            :props="productTypeProps"
            clearable
            filterable
            style="width: 220px"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item label="上下限">
          <el-select v-model="filters.limitType" placeholder="请选择" style="width: 160px">
            <el-option label="全部" value="all" />
            <el-option label="低于下限" value="lower" />
            <el-option label="高于上限" value="upper" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-space>
            <el-button @click="handleReset">重置</el-button>
            <el-button type="primary" @click="handleSearch">查询</el-button>
          </el-space>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-card">
      <div class="table-toolbar">
        <el-space>
          <el-button @click="handleExport">导出</el-button>
          <el-button @click="fetchData">刷新</el-button>
        </el-space>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        height="520px"
        style="width: 100%"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productCode" label="货品编号" min-width="120">
          <template #default="{ row }">
            <el-link type="primary" :underline="false">{{ row.productCode }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="货品名称" min-width="140" show-overflow-tooltip />
        <el-table-column prop="productSpecification" label="规格型号" min-width="120" />
        <el-table-column prop="unitName" label="单位" width="80" />
        <el-table-column prop="productTypeName" label="货品类型" min-width="120" />
        <el-table-column prop="currentStock" label="当前库存" width="110" align="right" />
        <el-table-column prop="lowerLimit" label="库存下限" width="110" align="right" />
        <el-table-column prop="upperLimit" label="库存上限" width="110" align="right" />
        <el-table-column label="低于下限" width="120" align="center">
          <template #default="{ row }">
            <span :class="{ warning: row.lowerWarning }">
              {{ formatPercent(row.lowerPercentage) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="高于上限" width="120" align="center">
          <template #default="{ row }">
            <span :class="{ warning: row.upperWarning }">
              {{ formatPercent(row.upperPercentage) }}
            </span>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="page.pageIndex"
          v-model:page-size="page.pageSize"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import myaxios from '@/http/MyAxios'

interface InventoryItem {
  productId: number
  productCode: string
  productName: string
  productSpecification: string
  unitName: string
  productTypeName: string
  currentStock: number
  lowerLimit: number
  upperLimit: number
  lowerPercentage: number
  upperPercentage: number
  lowerWarning: boolean
  upperWarning: boolean
}

const loading = ref(false)
const tableData = ref<InventoryItem[]>([])

const filters = reactive({
  productKeyword: '',
  productTypeId: null as number | null,
  limitType: 'all',
  currentStockMin: undefined as number | undefined,
  currentStockMax: undefined as number | undefined
})

const productTypeOptions = ref<any[]>([])
const productTypeProps = {
  value: 'producttypeId',
  label: 'producttypeName',
  children: 'children',
  checkStrictly: true,
  emitPath: false
}

const page = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

const fetchData = async () => {
  loading.value = true
  try {
    const params: any = {
      pageIndex: page.pageIndex,
      pageSize: page.pageSize,
      productName: filters.productKeyword || undefined,
      productTypeId: filters.productTypeId || undefined,
      currentStockMin: filters.currentStockMin || undefined,
      currentStockMax: filters.currentStockMax || undefined
    }
    const res = await myaxios.get('/api/Inventory/GetInventoryPage', { params })
    if (res.data?.code === 200) {
      const list = res.data.data?.data || []
      page.total = res.data.data?.listCount || list.length
      tableData.value = list
        .map((item: any) => transformItem(item))
        .filter((item: InventoryItem) => {
          if (filters.limitType === 'lower') {
            return item.lowerWarning
          }
          if (filters.limitType === 'upper') {
            return item.upperWarning
          }
          return true
        })
    }
  } catch (err) {
    console.error(err)
    ElMessage.error('获取库存数据失败')
  } finally {
    loading.value = false
  }
}

const transformItem = (item: any): InventoryItem => {
  const current = Number(item.currentStock || 0)
  const lower = Number(item.lowerLimit || 0)
  const upper = Number(item.upperLimit || 0)

  const lowerPercentage =
    lower > 0 && current < lower ? ((lower - current) / lower) * 100 : 0
  const upperPercentage =
    upper > 0 && current > upper ? ((current - upper) / upper) * 100 : 0

  return {
    productId: item.productId,
    productCode: item.productCode,
    productName: item.productName,
    productSpecification: item.productSpecification,
    unitName: item.unitName,
    productTypeName: item.productTypeName,
    currentStock: current,
    lowerLimit: lower,
    upperLimit: upper,
    lowerPercentage,
    upperPercentage,
    lowerWarning: lowerPercentage >= 10,
    upperWarning: upperPercentage >= 10
  }
}

const handleReset = () => {
  filters.productKeyword = ''
  filters.productTypeId = null
  filters.limitType = 'all'
  filters.currentStockMin = undefined
  filters.currentStockMax = undefined
  page.pageIndex = 1
  fetchData()
}

const handleSearch = () => {
  page.pageIndex = 1
  fetchData()
}

const handleSizeChange = (size: number) => {
  page.pageSize = size
  page.pageIndex = 1
  fetchData()
}

const handleCurrentChange = (index: number) => {
  page.pageIndex = index
  fetchData()
}

const handleExport = () => {
  ElMessage.info('导出功能开发中')
}

const loadProductTypes = async () => {
  try {
    const res = await myaxios.get('/api/Product/GetProductType')
    if (res.data?.code === 200) {
      productTypeOptions.value = buildTree(res.data.data || [], 'producttypeId', 'producttypeParentid')
    }
  } catch (error) {
    console.error('获取货品类型失败', error)
  }
}

const buildTree = (list: any[], idKey: string, parentKey: string) => {
  const map: Record<string, any> = {}
  const tree: any[] = []
  list.forEach((item) => {
    map[item[idKey]] = { ...item, children: [] }
  })
  list.forEach((item) => {
    const parentId = item[parentKey]
    if (parentId && map[parentId]) {
      map[parentId].children.push(map[item[idKey]])
    } else {
      tree.push(map[item[idKey]])
    }
  })
  return tree
}

const formatPercent = (value: number) => {
  if (!value) return '0.00%'
  return `${value.toFixed(2)}%`
}

onMounted(() => {
  loadProductTypes()
  fetchData()
})
</script>

<style scoped>
.inventory-warning-page {
  padding: 16px;
}

.filter-card {
  margin-bottom: 12px;
}

.table-card .table-toolbar {
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
}

.pagination {
  margin-top: 12px;
  text-align: right;
}

.warning {
  color: #f56c6c;
  font-weight: 600;
}
</style>


